// documentStore.js
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { departments, users } from '@/stores/mockData.js';

export const useDocumentStore = defineStore('document', () => {
    const documents = ref([]);
    const currentUser = ref(users[0]); // 假设第一个用户是当前登录用户

    // 生成公文或草稿的通用逻辑
    const generateDocumentData = (title, content, receiverIds) => {
        const validReceiverIds = Array.isArray(receiverIds) ? receiverIds : [];

        if (validReceiverIds.length === 0) {
            console.warn('未选择接收人');
            return null;
        }

        const sender = currentUser.value;
        const receivers = users.filter(u => validReceiverIds.includes(u.id));

        const readStatus = receivers.map(r => ({
            userId: r.id,
            read: false,
            readTime: null
        }));

        return {
            title,
            content,
            sender,
            receivers,
            readStatus,
            circulationTime: new Date().toISOString().slice(0, 16).replace('T', ' ')
        };
    };

    //  1. 保存草稿
    const saveDraft = ({ title, content, recipientIds }) => {
        const data = generateDocumentData(title, content, recipientIds);
        if (!data) return false;

        const draft = {
            id: documents.value.length + 1,
            ...data,
            status: 'draft',
            isDraft: true
        };

        documents.value.push(draft);
        return true;
    };

    //  2. 更新草稿
    const updateDraft = (draftId, { title, content, recipientIds }) => {
        const draft = documents.value.find(d => d.id === draftId && d.isDraft);
        if (!draft) return false;

        const data = generateDocumentData(title, content, recipientIds);
        if (!data) return false;

        Object.assign(draft, data, { id: draftId, status: 'draft', isDraft: true });
        return true;
    };

    //  3. 删除草稿
    const deleteDraft = (draftId) => {
        const index = documents.value.findIndex(d => d.id === draftId && d.isDraft);
        if (index > -1) {
            documents.value.splice(index, 1);
            return true;
        }
        return false;
    };

    // 4. 发送公文（从草稿发送）
    const createCirculation = (title, content, receiverIds) => {
        const data = generateDocumentData(title, content, receiverIds);
        if (!data) return null;

        const newDocument = {
            id: documents.value.length + 1,
            ...data,
            status: 'pending',
            isDraft: false
        };

        documents.value.push(newDocument);
        return newDocument;
    };

    // 从草稿发布为正式公文
    const publishDraft = (draftId) => {
        const draftIndex = documents.value.findIndex(d => d.id === draftId && d.isDraft);
        if (draftIndex === -1) return false;

        const draft = documents.value[draftIndex];

        const publishedDoc = {
            ...draft,
            id: documents.value.length + 1,
            status: 'pending',
            isDraft: false,
            circulationTime: new Date().toISOString().slice(0, 16).replace('T', ' ')
        };

        // 从草稿列表移除
        documents.value.splice(draftIndex, 1);
        // 加入正式公文列表
        documents.value.push(publishedDoc);

        return true;
    };
    //  5. 获取草稿箱
    const getDrafts = () => {
        return documents.value.filter(doc => doc.isDraft && doc.sender.id === currentUser.value.id);
    };

    //  6. 获取发件箱（已发送）
    const getOutbox = () => {
        return documents.value.filter(doc => !doc.isDraft && doc.sender.id === currentUser.value.id);
    };

    //  7. 获取收件箱
    const getInbox = () => {
        return documents.value.filter(doc =>
            !doc.isDraft &&
            doc.receivers.some(r => r.id === currentUser.value.id)
        );
    };

    //  8. 获取待阅（未读）
    const getPending = () => {
        return documents.value.filter(doc =>
            !doc.isDraft &&
            doc.receivers.some(r => r.id === currentUser.value.id) &&
            !doc.readStatus.find(rs => rs.userId === currentUser.value.id)?.read
        );
    };

    //  9. 标记为已读
    const markAsRead = (docId) => {
        const doc = documents.value.find(d => d.id === docId);
        if (doc) {
            const readStatus = doc.readStatus.find(rs => rs.userId === currentUser.value.id);
            if (readStatus && !readStatus.read) {
                readStatus.read = true;
                readStatus.readTime = new Date().toISOString().slice(0, 16).replace('T', ' ');
                doc.status = doc.readStatus.every(rs => rs.read) ? 'completed' : 'pending';
            }
        }
    };

    return {
        documents,
        departments,
        users,
        currentUser,
        saveDraft,        //  保存草稿
        updateDraft,      //  更新草稿
        deleteDraft,      //  删除草稿
        createCirculation, //  发送公文
        getDrafts,        //  获取草稿列表
        publishDraft,     //  发布草稿为正式公文
        getOutbox,
        getInbox,
        getPending,
        markAsRead
    };
});
